﻿using Common.Exceptions;
using Common.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wallpaper.Data.Dal;
using Wallpaper.Data.IDal;
using Wallpaper.Models.DTOs.Requests.Carousel;
using Wallpaper.Models.DTOs.Responses.Carousel;
using Wallpaper.Models.Entities;
using Wallpaper.Services.IService;

namespace Wallpaper.Services.Service
{
    public class CarouselService : ICarouselService
    {

        readonly ICarouselDal _carouselDal;

        public CarouselService(ICarouselDal carouselDal)
        {
            _carouselDal = carouselDal;
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="carouselRequest"></param>
        /// <returns></returns>
        /// <exception cref="BusinessException"></exception>
        public async Task<bool> CreateAsync(CarouselRequest carouselRequest)
        {
            if (string.IsNullOrWhiteSpace(carouselRequest.CarouselUrl))
            {
                throw new BusinessException("轮播图URL不能为空", 400);
            }

            if (carouselRequest.SortOrder < 0)
            {
                throw new BusinessException("排序值不能为负数", 400);
            }

            Carousel carousel = new Carousel
            {
                Id = Guid.NewGuid().ToString(),
                Title= carouselRequest.Title,
                SortOrder = carouselRequest.SortOrder,
                CarouselUrl = carouselRequest.CarouselUrl,
                IsEnabled = carouselRequest.IsEnabled
            };

            return await _carouselDal.CreateEntityAsync(carousel);
        }

        /// <summary>
        /// 根据id删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> DeleteAsync(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                throw new BusinessException("轮播图ID不能为空", 400);
            }
            Carousel carousel = await _carouselDal.GetByIdAsync(id);
            if (carousel == null)
            {
                throw new DataNotFoundException("轮播图不存在或数据异常");
            }

            return await _carouselDal.DeleteEntityAsync(carousel);
        }
        

        /// <summary>
        /// 获取轮播图
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<BannerResponse>> GetBannersAsync()
        {
              var query= _carouselDal.GetQueryable().Where(c=>c.IsEnabled&&!c.IsDeleted);
                var response = await query.Select(b => new BannerResponse
                {
                    Id = b.Id,
                    CarouselUrl = b.CarouselUrl,
                    Title = b.Title
                }).ToListAsync();
                return response;
        }


        /// <summary>
        /// 分页搜索
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PagedResult<CarouselPageResponse>> PageAsync(CarouselQueryRequest request)
        {
            var query = _carouselDal.GetQueryable();
            var baseSql = query.ToQueryString();
            Console.WriteLine(baseSql);
            // 关键词搜索
            if (!string.IsNullOrWhiteSpace(request.Keyword))
            {
                query = query.Where(c => c.Title.Contains(request.Keyword));
            }

            // 启用状态筛选
            if (request.IsEnabled.HasValue)
            {
                query = query.Where(r => r.IsEnabled == request.IsEnabled.Value);
            }
            // 排序（按创建时间降序）
            query = query.OrderBy(r => r.SortOrder)
            .ThenByDescending(r => r.CreatedAt);
            // 获取总数
            var totalCount = await query.CountAsync();

            // 分页
            var items = await query
                .Skip((request.Page - 1) * request.PageSize)
                .Take(request.PageSize)
                .Select(c => new CarouselPageResponse
                {
                    
                    Id=c.Id,
                    Title=c.Title,
                    CarouselUrl=c.CarouselUrl,
                    SortOrder=c.SortOrder,
                    IsEnabled=c.IsEnabled,
                    CreatedTime=c.CreatedAt,
                    UpdatedTime=c.UpdatedAt
                   
                }).ToListAsync();

            return new PagedResult<CarouselPageResponse>
            {
                Page = request.Page,
                PageSize = request.PageSize,
                TotalCount = totalCount,
                Items = items
            };
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="carouselRequest"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<bool> UpdateAsync(string carouselId, CarouselRequest request)
        {
            if (string.IsNullOrWhiteSpace(carouselId))
                throw new BusinessException("轮播图ID不能为空", 400);

            var existingCarousel = await _carouselDal.GetByIdAsync(carouselId);
            if (existingCarousel == null)
            {
                throw new DataNotFoundException("轮播图不存在或数据异常");
            }


            // 只更新有值的字段（简单判断）
            if (!string.IsNullOrWhiteSpace(request.Title))
            {
                existingCarousel.Title = request.Title;
            }

            // 只更新有值的字段（简单判断）
            if (!string.IsNullOrWhiteSpace(request.CarouselUrl))
            {
                existingCarousel.CarouselUrl = request.CarouselUrl;
            }

            // 假设排序值>=0
            if (request.SortOrder >= 0)
            {
                existingCarousel.SortOrder = request.SortOrder;
            } 
                
            // bool 值直接更新，因为总是有默认值
            existingCarousel.IsEnabled = request.IsEnabled;

            return await _carouselDal.UpdateEntityAsync(existingCarousel);
        }
    }
}
